package com.hmall.delay;

import com.alibaba.fastjson.JSONObject;
import com.hmall.delay.model.Message;
import com.hmall.mapper.MallOrderMapper;
import com.hmall.mapper.SysUserMapper;
import com.hmall.model.MallOrder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;

//@SpringBootTest
//@RunWith(SpringRunner.class)
@RestController
@Api("延时队列功能")
@RequestMapping("/redisMQ/")
public class MQController {

    @Resource
    private RedisMQ redisMQ;

    @Value("${mq.queue.payment}")
    private String MQ_QUEUE_PAYMENT;

    @Autowired
    MallOrderMapper orderMapper;

    @Autowired
    SysUserMapper userMapper;

    //low 延时队列
    //暂时使用schedule+单线程+redis zset + redis list实现
    //可进化为 zookeeper job + 多线程 + redis 实现
    @PostMapping("tradeWarning")
    @ApiOperation(value = "交易预警" ,notes = "订单12小时预警一次")
    public void testMq(Long orderNo) {



        MallOrder mallOrder = orderMapper.selectAllByOrderNo(orderNo);

        //用户的username就是手机号
        String phone = userMapper.selectByPrimaryKey(mallOrder.getUserId()).getUsername();

        Integer customerUserId = mallOrder.getUserId();

        Date date = mallOrder.getUpdateTime();

        Integer status = 3;

        String value = "" + orderNo;

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg", "手机号为" + phone + "订单号为" + orderNo + "的订单还有12小时交易将结束，请及时联系用户了解情况");
        jsonObject.put("customerUserId", customerUserId);
        jsonObject.put("date", date);
        jsonObject.put("status", status);
        jsonObject.put(value, value);

        //队列id
        String seqId = UUID.randomUUID().toString();
        // 将有效信息放入消息队列和消息池中
        Message message = new Message();
        message.setBody(jsonObject.toJSONString());
        // 可以添加延迟配置
        //48小时 提前12小时
        message.setDelay(1000 * 60 * 60 * 36);
        //设置标题
        message.setTopic("SMS");
        //创建时间
        message.setCreateTime(System.currentTimeMillis());
        message.setId(seqId);
        // 设置消息池ttl，防止长期占用
        //redis至少保存48小时
        message.setTtl(60 * 60 * 24 * 50);
        //0表示延时队列
        message.setStatus(0);
        //设置优先级
        message.setPriority(0);
        //加到消息池里
        redisMQ.addMsgPool(message);

        redisMQ.enMessage(MQ_QUEUE_PAYMENT, message.getCreateTime() + message.getDelay() + message.getPriority(), message.getId());
    }
}
